Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

245
Vistas
Laravel 5.8: $bal->balance is getting null

I want to get a value of balance column from a pivot table called user_wallet which goes like this:

enter image description here

So I wrote this at the Controller:

$bal = Wallet::with("users")->whereHas('users', function ($query) use ($wallet_id, $user_id) {
    $query->where('wallet_id', $wallet_id);
    $query->where('user_id', $user_id);
})->first();

But when I do dd($bal->balance), I get null!

So why is that? How can I get the balance value based on user_id and wallet_id properly?

Here is also the relationships between User model and Wallet model:

User.php

public function wallets()
{
    return $this->belongsToMany(Wallet::class, 'user_wallet', 'user_id', 'wallet_id')->withPivot('balance');
}

Wallet.php

public function users()
{
    return $this->belongsToMany(User::class, 'user_wallet', 'wallet_id', 'user_id');
}

I would really appreciate any idea or suggestion from you guys...

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Your query is supposed to be like below. Becuase the relation you're making is with users table not user_wallet.

$bal = Wallet::with("users")
    ->whereHas('users', function ($query) use ($user_id) {
        $query->where('id',$user_id);
    })
    ->where('id', $wallet_id)
    ->first();

You can make a simple query as well:

$bal = DB::table('user_wallet')
    ->where('wallet_id', $wallet_id)
    ->where('user_id', $user_id)
    ->first();

if (!empty($bal)) {
    $balance = $bal->balance;
}
over 4 years ago · Santiago Trujillo Denunciar

0

Since it is a many to many relationship, for getting the pivot table you loop like below:

@foreach($bal as $key => $value)
    {{$value->pivot->balance}}
@endforeach

or if it is a single item then you can do like:

$user = $bal->users()->first();

$user->pivot->balance;

or

$user = $bal->users->first();

$user->pivot->balance;

if still need directly then, as suggested by @Dilip Hirapara answer.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda